package com.zlfund.cat.zjgsmk.ui.user;

import android.content.Context;
import android.text.TextUtils;

import com.zlfund.cat.zjgsmk.bean.UserBean;
import com.zlfund.cat.zjgsmk.constant.Constants;
import com.zlfund.cat.zjgsmk.constant.EventBusConstant;
import com.zlfund.cat.zjgsmk.constant.MessageEvent;
import com.zlfund.cat.zjgsmk.controller.NoLoginHelper;
import com.zlfund.cat.zjgsmk.ui.base.ZApplication;
import com.zlfund.cat.zjgsmk.util.SpUtils;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by chenj on 2017/9/21 0021.
 */

public class UserManager {

    private static UserBean mUserBean;

    public static boolean isLogin(){
        if (mUserBean == null){
            mUserBean = singleTon();
        }
        return mUserBean != null && mUserBean.getR().getAuth() != null;
    }

    public static String getAuth(){
        if (mUserBean == null){
            mUserBean = singleTon();
        }
        if (mUserBean == null || mUserBean.getR().getAuth() == null){
            return null;
        }else {
            return mUserBean.getR().getAuth();
        }
    }

    public static void exit(){
        clearUserInfo();
        ZApplication.mContext.setLoginService(new NoLoginHelper());
        EventBus.getDefault().post(new MessageEvent(EventBusConstant.MAINACTIVITYREFRESHDATA));
    }

    private static void clearUserInfo(){
        SpUtils.clear(ZApplication.mContext, SpUtils.ACCOUNTINFO);
        mUserBean = null;
    }

    public static UserBean singleTon(){
        if (mUserBean == null){
            synchronized (UserManager.class){
                if (mUserBean == null){
                    mUserBean = getUserBean();
                }
            }
        }
        return mUserBean;
    }

    private static UserBean getUserBean() {
        Context context = ZApplication.mContext;
        if (TextUtils.isEmpty(SpUtils.getStringFromAccount(context, "auth"))){
            return null;
        }
        UserBean userBean = new UserBean();
        UserBean.RBean rBean = new UserBean.RBean();
        rBean.setId(SpUtils.getStringFromAccount(context,"id"));
        rBean.setNamed(SpUtils.getStringFromAccount(context,"named"));
        rBean.setBirthday(SpUtils.getStringFromAccount(context,"birthday"));
        rBean.setSex(SpUtils.getStringFromAccount(context,"sex"));
        rBean.setName(SpUtils.getStringFromAccount(context,"name"));
        rBean.setCard(SpUtils.getStringFromAccount(context,"card"));
        rBean.setIco(SpUtils.getStringFromAccount(context,"ico"));
        rBean.setAvatar(SpUtils.getStringFromAccount(context,"avatar"));
        rBean.setBrief(SpUtils.getStringFromAccount(context,"brief"));
        rBean.setAuth(SpUtils.getStringFromAccount(context,"auth"));
        userBean.setR(rBean);
        return userBean;
    }

}
